<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
/*        function onclickFun(){
            var usernameObj = document.getElementById("username");
            // alert(usernameObj.type);
            // alert(usernameObj.value);
            var usernameText = usernameObj.value;

            // 验证过程
            var patt = /^\w{5,12}$/;

            let usernameSpanObj = document.getElementById("usernameSpan");

            if (patt.test(usernameText)) {
                usernameSpanObj.innerHTML = "用户名合法!";
            } else {
                usernameSpanObj.innerHTML = "用户名不合法!";
            }
        }

        window.onload = function (){
            let usernameObj = document.getElementById("username");

            usernameObj.onblur = function (){
                onclickFun();
            }
        }*/

        window.onload = function () {
            var usernameObj = document.getElementById("username");

            usernameObj.onblur = function (){
                // 必须放在里面!!!放在外面就是出错
                var usernameText = usernameObj.value;

                var patt = /^\w{5,12}$/;

                let usernameSpanObj = document.getElementById("usernameSpan");

                if (patt.test(usernameText)) {
                    usernameSpanObj.innerHTML = "用户名合法!";
                } else {
                    usernameSpanObj.innerHTML = "用户名不合法!";
                }
            }
        }


    </script>
</head>
<body>
    用户名: <input type="text" id="username">
    <span id="usernameSpan" style="color: red;"></span>
    <button onclick="onclickFun();">验证</button>
</body>
</html>